<template>
  <InfoTable
    title="手机号信息"
    :data="paginatedPhoneNumbers"
    :columns="columns"
    :pagination="pagination"
    key-field="phone"
    search-placeholder="请输入手机号"
    create-button-text="创建手机号"
    :selected-items="selectedPhoneNumbers"
    @search="handleSearch"
    @create="handleCreate"
    @action="handleAction"
    @page-change="handlePageChange"
    @batch-delete="handleBatchDelete"
    @toggle-item-selection="togglePhoneNumberSelection"
    @toggle-select-all="toggleSelectAll"
    @clear-selection="clearSelection"
  />
  
  <!-- 编辑手机号信息弹窗 -->
  <EditPhoneNumber 
    v-model:visible="editDialogVisible" 
    @success="handleEditSuccess"
    ref="editPhoneNumberRef"
  />
  
  <!-- 创建手机号信息弹窗 -->
  <CreatePhoneNumber 
    v-model:visible="createDialogVisible" 
    @success="handleCreateSuccess"
    ref="createPhoneNumberRef"
  />
</template>

<script>
import InfoTable from '@/components/InfoTable.vue'
import EditPhoneNumber from './EditPhoneNumber.vue'
import CreatePhoneNumber from './CreatePhoneNumber.vue'
import { getPhoneNumberInfo, deletePhoneNumberInfo, deleteBatchPhoneNumberInfo, deleteCustomerPhone } from '@/apis/phoneNumber'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'PhoneNumberInfoTemplate',
  components: {
    InfoTable,
    EditPhoneNumber,
    CreatePhoneNumber
  },
  data() {
    return {
      allPhoneNumbers: [],
      searchQuery: '',
      loading: false,
      selectedPhoneNumbers: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      columns: [
        { key: 'phone', title: '手机号' },
        { key: 'phoneAddress', title: '归属地' },
        { key: 'status', title: '状态', format: 'status' },
        { key: 'createTime', title: '创建时间' },
        { key: 'updateTime', title: '更新时间' }
      ],
      // 控制编辑弹窗显示
      editDialogVisible: false,
      // 控制创建弹窗显示
      createDialogVisible: false
    }
  },
  computed: {
    // 分页后的手机号数据
    paginatedPhoneNumbers() {
      const start = (this.pagination.current - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.filteredPhoneNumbers.slice(start, end);
    },
    // 根据搜索条件过滤后的手机号数据
    filteredPhoneNumbers() {
      let filtered = this.allPhoneNumbers;
      
      // 如果有搜索查询，按搜索结果筛选
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.trim().toLowerCase();
        filtered = filtered.filter(phoneNumber => 
          (phoneNumber.phone && phoneNumber.phone.toLowerCase().includes(query))
        );
      }
      
      return filtered;
    },
    // 检查是否所有项目都被选中
    areAllItemsSelected() {
      return this.paginatedPhoneNumbers.length > 0 && 
             this.selectedPhoneNumbers.length === this.paginatedPhoneNumbers.length;
    }
  },
  methods: {
    async loadPhoneNumberData() {
      this.loading = true;
      try {
        const res = await getPhoneNumberInfo();
        console.log('手机号数据:', res);
        // 根据后端接口返回的数据结构处理数据
        if (res && res.code === 0 && res.data) {
          // 直接使用后端返回的 data 数据
          this.allPhoneNumbers = Array.isArray(res.data) ? res.data : [];
          this.pagination.total = this.allPhoneNumbers.length;
        }
      } catch (error) {
        console.error('获取手机号数据失败:', error);
        // 出错时清空数据
        this.allPhoneNumbers = [];
      } finally {
        this.loading = false;
      }
    },
    handleSearch(query) {
      console.log('搜索手机号:', query);
      this.searchQuery = query;
      // 重置到第一页
      this.pagination.current = 1;
    },
    handleCreate() {
      console.log('创建手机号');
      this.createDialogVisible = true;
    },
    handleAction({ action, item }) {
      switch (action) {
        case 'view':
          console.log('查看手机号:', item);
          break;
        case 'edit':
          console.log('编辑手机号:', item);
          this.handleEdit(item);
          break;
        case 'delete':
          console.log('删除手机号:', item);
          this.handleDelete(item);
          break;
      }
    },
    // 处理编辑操作
    handleEdit(item) {
      this.$refs.editPhoneNumberRef.setFormData(item);
      this.editDialogVisible = true;
    },
    // 编辑成功回调
    handleEditSuccess() {
      this.loadPhoneNumberData(); // 重新加载数据
    },
    // 创建成功回调
    handleCreateSuccess() {
      this.loadPhoneNumberData(); // 重新加载数据
    },
    // 处理删除操作
    async handleDelete(item) {
      try {
        await ElMessageBox.confirm(
          `确定要删除手机号 ${item.phone} 吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        // 先删除手机号与客户的关联关系
        await deleteCustomerPhone(item.phone);
        
        // 再删除手机号信息
        const res = await deletePhoneNumberInfo(item.phone);
        if (res.code === 0) {
          ElMessage.success('删除成功');
          this.loadPhoneNumberData(); // 重新加载数据
          // 从选中项中移除
          const index = this.selectedPhoneNumbers.indexOf(item.phone);
          if (index > -1) {
            this.selectedPhoneNumbers.splice(index, 1);
          }
        } else {
          ElMessage.error(res.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除手机号失败:', error);
          ElMessage.error('删除手机号失败');
        }
      }
    },
    handlePageChange(page) {
      console.log('切换到页面:', page);
      this.pagination.current = page;
      // 清除选中项
      this.clearSelection();
    },
    // 处理批量删除
    async handleBatchDelete(selectedItems) {
      if (selectedItems.length === 0) {
        ElMessage.warning('请至少选择一条记录');
        return;
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedItems.length} 个手机号吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        // 先删除每个手机号的关联关系
        for (const phone of selectedItems) {
          await deleteCustomerPhone(phone);
        }
        
        // 将选中的手机号数组转换为逗号分隔的字符串
        const ids = selectedItems.join(',');
        const res = await deleteBatchPhoneNumberInfo(ids);
        if (res.code === 0) {
          ElMessage.success('批量删除成功');
          this.loadPhoneNumberData(); // 重新加载数据
          // 清除选中项
          this.selectedPhoneNumbers = [];
        } else {
          ElMessage.error(res.msg || '批量删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除手机号失败:', error);
          ElMessage.error('批量删除手机号失败');
        }
      }
    },
    // 切换项目选择状态
    togglePhoneNumberSelection(phone) {
      const index = this.selectedPhoneNumbers.indexOf(phone);
      if (index > -1) {
        // 如果已选中，则取消选中
        this.selectedPhoneNumbers.splice(index, 1);
      } else {
        // 如果未选中，则添加到选中列表
        this.selectedPhoneNumbers.push(phone);
      }
    },
    // 切换全选状态
    toggleSelectAll() {
      if (this.selectedPhoneNumbers.length === this.paginatedPhoneNumbers.length) {
        // 如果已全选，则取消全选
        this.selectedPhoneNumbers = [];
      } else {
        // 如果未全选，则全选当前页的所有项目
        this.selectedPhoneNumbers = this.paginatedPhoneNumbers.map(item => item.phone);
      }
    },
    // 清除选中项
    clearSelection() {
      this.selectedPhoneNumbers = [];
    }
  },
  mounted() {
    this.loadPhoneNumberData();
  },
  watch: {
    allPhoneNumbers() {
      // 数据变化时更新总数量
      this.pagination.total = this.allPhoneNumbers.length;
      // 数据变化时清除选中项中已不存在的项
      this.selectedPhoneNumbers = this.selectedPhoneNumbers.filter(phone => 
        this.allPhoneNumbers.some(item => item.phone === phone)
      );
    }
  }
}
</script>

<style scoped>
</style>